package com.rabc.web.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabc.web.entity.SysMenu;
import com.rabc.web.entity.SysRoleMenu;
import com.rabc.web.entity.SysUser;
import com.rabc.web.mapper.SysRoleMenuMapper;
import com.rabc.web.service.SysMenuService;
import com.rabc.web.mapper.SysMenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 27632
* @description 针对表【sys_menu(菜单表)】的数据库操作Service实现
* @createDate 2024-07-04 23:05:40
*/
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService{

    @Autowired
    SysMenuMapper sysMenuMapper;

    @Autowired
    SysRoleMenuMapper roleMenuMapper;

    @Override
    public List<SysMenu> selectMenuList(SysMenu sysMenu) {
        return sysMenuMapper.selectMenuList(sysMenu);
    }

    /**
     *
     * @param sysMenu 菜单对象
     * @return treeDate  树形结构菜单
     */
    @Override
    public List<SysMenu> selectMenuTree(SysMenu sysMenu) {
        //获取跟节点
     //   List<SysMenu> treeTop = this.baseMapper.selectList(new QueryWrapper<SysMenu>().eq("parent_id",0));
        List<SysMenu> menuList = sysMenuMapper.selectMenuList(sysMenu);
        List<SysMenu> treeDate = menuList.stream().filter(f->f.getParentId().equals("0")).map(m -> {
            m.setChildren(getMenuTreeNode(m, menuList));
            return m;

        }).collect(Collectors.toList());
        return treeDate;
    }

    @Override
    public List<String> selectMenuListByRoleId(String roleId) {
      List<SysRoleMenu> sysRoleMenuList = roleMenuMapper.selectList(new QueryWrapper<SysRoleMenu>()
              .eq("role_id", roleId));
        List<String> menuIds = sysRoleMenuList.stream().map(m -> {
            return m.getMenuId();
        }).collect(Collectors.toList());

        return menuIds;
    }

    @Override
    public List<SysMenu> selectMenuListByUser(SysUser user) {
        return Collections.emptyList();
    }

    private List<SysMenu> getMenuTreeNode(SysMenu menu,List<SysMenu> menuList){
        List<SysMenu> TreeNode = menuList.stream().filter(f->f.getParentId().equals(menu.getMenuId()))
                .peek(item -> {

                        //System.out.println("子菜单");
                        item.setChildren(getMenuTreeNode(item,menuList));
        }).collect(Collectors.toList());

        return TreeNode;
    }
}




